<template>
  <div class="app-container">
    <div class="toolbar">
      <el-input id="tipinput" v-model="keyword" placeholder="输入地点检索" clearable @keyup.enter="searchByKeyword" />
      <el-button type="primary" @click="searchByKeyword" :disabled="!keyword">确定</el-button>
      <!-- 移除顶部经纬度输入框，改为地图左上角悬浮显示 -->
      <div class="actions">
        <el-button type="primary" plain @click="saveAndReturn" :disabled="!selected">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="content">
      <div id="container" class="map">
        <div class="coord-overlay">{{ selectedText || '未选点' }}</div>
      </div>
      <div id="panel" class="panel"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AMapLoader from '@amap/amap-jsapi-loader'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const keyword = ref('')
const map = ref(null)
let placeSearch = null
let autoComplete = null
let marker = null
const selected = ref(null) // {lng, lat, address}

// 展示经纬度文本
const selectedText = computed(() => {
  if (!selected.value) return ''
  const { lng, lat } = selected.value
  return `${lng.toFixed(6)}, ${lat.toFixed(6)}`
})

onMounted(async () => {
  const key = import.meta.env.VITE_AMAP_KEY || ''
  if (!key) {
    console.warn('缺少高德Key: 请在 .env.development 配置 VITE_AMAP_KEY')
    return
  }
  const AMap = await AMapLoader.load({
    key,
    version: '2.0',
    plugins: ['AMap.ToolBar','AMap.AutoComplete','AMap.PlaceSearch','AMap.Geocoder']
  })

  map.value = new AMap.Map('container', {
    viewMode: '2D',
    zoom: 12,
    center: [116.397428, 39.90923]
  })

  map.value.addControl(new AMap.ToolBar())

  // 结果面板 + 搜索
  placeSearch = new AMap.PlaceSearch({ pageSize: 10, map: map.value, panel: 'panel' })
  autoComplete = new AMap.AutoComplete({ input: 'tipinput' })
  autoComplete.on('select', e => { placeSearch.search(e.poi.name) })

  const geocoder = new AMap.Geocoder()

  // 若从表单传入坐标，解析后居中并逆地理
  const rawLoc = route.query?.location ? decodeURIComponent(String(route.query.location)) : ''
  const match = rawLoc.match(/(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)/)
  if (match) {
    const lng = parseFloat(match[1])
    const lat = parseFloat(match[2])
    marker = new AMap.Marker({ position: [lng, lat] })
    map.value.add(marker)
    map.value.setZoom(16)
    map.value.setCenter([lng, lat])
    geocoder.getAddress([lng, lat], (status, result) => {
      const address = status === 'complete' && result.regeocode ? result.regeocode.formattedAddress : ''
      selected.value = { lng, lat, address }
    })
  }

  // 点击地图选点
  map.value.on('click', (e) => {
    const { lng, lat } = e.lnglat
    if (!marker) {
      marker = new AMap.Marker({ position: [lng, lat] })
      map.value.add(marker)
    } else {
      marker.setPosition([lng, lat])
    }
    geocoder.getAddress([lng, lat], (status, result) => {
      const address = status === 'complete' && result.regeocode ? result.regeocode.formattedAddress : ''
      selected.value = { lng, lat, address }
    })
  })
})

function searchByKeyword() {
  const kw = (keyword.value || '').trim()
  if (!kw) {
    ElMessage.warning('请输入要检索的地点')
    return
  }
  if (placeSearch) {
    placeSearch.search(kw)
  }
}

function confirmSelect() {
  if (!selected.value) return
  localStorage.setItem('MANGE_MAP_SELECTION', JSON.stringify(selected.value))
  // 使用返回历史，避免固定路径导致空白页
  router.back()
}

// 保存按钮与“确定”一致，这里提供明确的保存语义
function saveAndReturn() {
  confirmSelect()
}

function goBack() {
  // 仅返回，不写入选点数据
  router.back()
}
</script>

<style scoped>
.app-container { display: flex; flex-direction: column; height: 100%; }
.toolbar { display: flex; gap: 12px; align-items: center; margin-bottom: 8px; }
.content { display: grid; grid-template-columns: 1fr 320px; gap: 8px; height: calc(100vh - 160px); }
.map { width: 100%; height: 100%; position: relative; }
.coord-overlay { position: absolute; top: 8px; left: 8px; z-index: 10; background: rgba(255,255,255,0.95); padding: 6px 10px; border-radius: 4px; color: #333; font-size: 12px; box-shadow: 0 2px 6px rgba(0,0,0,0.1); }
.panel { width: 320px; height: 100%; overflow: auto; }
.actions { display: flex; gap: 8px; }
</style>